<?php

/**
 * Created by PhpStorm.
 * User: 侯佳
 * Date: 2017/9/28
 * Time: 16:08
 */
class StockWarningAction extends Action
{
    /**
     * 添加预警设置
     * @param $cuId “接收人的id”（多个，用逗号隔开）
     * @param $warnTime “预警时间”
     * @param $warnNum “警戒库存”
     */
    public function addWarning($cuId, $warnTime, $warnNum)
    {
        /** 1. 判断是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        Session::switchCustomer(0);
        $stock_warning = M('stock_warning');
        Session::switchCustomer(Session::$user["customerId"]);
        $data['cid'] = Session::$user["customerId"];
        $data['cuId'] = $cuId;
        $data['warnTime'] = $warnTime;
        $data['warnNum'] = $warnNum;
        $data['createTime'] = date('Y-m-d H:i:s', time());
        $data['updateTime'] = date('Y-m-d H:i:s', time());

        $res = $stock_warning->add($data);
        if ($res) {
            Output::instance()->object([
                'code' => 0,
                'msg' => '添加成功',
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '添加失败',
            ]);
        }
    }

    /**
     * 修改预警设置
     * @param $warningId 要修改的设置的id
     * @param $cuId
     * @param $warnTime
     * @param $warnNum
     */
    public function updateWarning($warningId, $cuId, $warnTime, $warnNum)
    {
        /** 1. 判断是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        Session::switchCustomer(0);
        $stock_warning = M('stock_warning');
        Session::switchCustomer(Session::$user["customerId"]);
        $where['id'] = $warningId;
        $data['cuId'] = $cuId;
        $data['warnTime'] = $warnTime;
        $data['warnNum'] = $warnNum;
        $data['updateTime'] = date('Y-m-d H:i:s', time());

        $res = $stock_warning->where($where)->save($data);
        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'msg' => '修改成功',
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '修改失败',
            ]);
        }
    }

    /**
     * 开关库存预警
     * @param $warningId
     * @param $isClose 0-开启/1-关闭
     */
    public function switchWarning($warningId, $isClose)
    {
        /** 1. 判断是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        Session::switchCustomer(0);
        $stock_warning = M('stock_warning');
        Session::switchCustomer(Session::$user["customerId"]);
        $where['id'] = $warningId;
        $data['isClose'] = $isClose;
        $res = $stock_warning->where($where)->save($data);

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'msg' => '操作成功',
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '操作失败',
            ]);
        }
    }

    /**
     * 获取本账号的预警设置
     */
    public  function getWarning()
    {
        /** 1. 判断是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        Session::switchCustomer(0);
        $stock_warning = M('stock_warning');
        Session::switchCustomer(Session::$user["customerId"]);
//        $where['cid'] = 3;
        $where['cid'] = Session::$user["customerId"];
        $warning = $stock_warning->where($where)->find();
        $warningId = $warning['id'];
        $cuId = $warning['cuId'];
        $warnTime = $warning['warnTime'];
        $warnNum = $warning['warnNum'];
        $isClose = $warning['isClose'];

        if ($warning) {
            Output::instance()->object([
                'code' => 0,
                'msg' => '获取成功',
                'data' => [
                    'warningId' => $warningId,
                    'cuId' => $cuId,
                    'warnTime' => $warnTime,
                    'warnNum' => $warnNum,
                    'isClose' => $isClose
                ]
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '获取失败',
            ]);
        }
    }

    /**
     * 预警检查,储存信息,定时任务每小时调用此接口
     */
    public function pushWarning()
    {
        $warningListData['startTime'] = date('Y-m-d H:i:s', time());
        $startTime = date('H:i');
        Session::switchCustomer(0);
        $stock_warning = M('stock_warning');
        $stock_warning_list = M('stock_warning_list');
        $stock_warning_result = M('stock_warning_result');
        $module_product = M('module_product');
        $module_product_speci = M('module_product_specification');
        Session::switchCustomer(Session::$user["customerId"]);

        /**查询需要发送预警的账号信息*/
        $warningWhere['deleted'] = 0;
        $warningWhere['isClose'] = 0;
        $stockWarning = $stock_warning
            ->where($warningWhere)
            ->field('cuId, cid, warnTime, warnNum')
            ->select();
        $warningListData['endTime'] = date('Y-m-d H:i:s', time());
        $stock_warning_list->add($warningListData);  //储存查询记录

        /**获取刚添加的预警检查记录id*/
        $warningListWhere['startTime'] = $warningListData['startTime'];
        $warningListId = $stock_warning_list
            ->where($warningListWhere)
            ->getField('id');

        //循环查询每个账号需要预警的商品
        foreach ($stockWarning as $key => $value) {

            /**过滤预警时间*/
            $time = strpos($value['warnTime'], $startTime);
            if(!is_numeric($time)){
                continue;
            }
            /**单规格商品*/
            $productWhere['fromCustomerId'] = array('eq', $value['cid']);
            $productWhere['inventoryCount'] = array('elt', $value['warnNum']);
            $productWhere['supportSpecification'] = array('eq', 0);
            $productList = $module_product->where($productWhere)->select();

            $cid = $value['cid'];
            $cuId = explode(',', $value['cuId']);

            $goodsList = [];
            foreach ($productList as $k => $product){
                $goodList = [
                    'name' => $product['name'],
                    'warningListId' => $warningListId,
                    'pid' => $product['id'],
                    'speciId' => null,
                    'inventoryCount' => $product['inventoryCount'],
                    'cid' => $value['cid'],
                    'cuId' => $value['cuId'],
                    'warnNum' => $value['warnNum'],
                    'serialNumber' => $product['serialNumber']
                ];
                $stock_warning_result->add($goodList);
                array_push($goodsList, $goodList);
            }
            /**
             * 多规格商品
             */
            $productWhere2['fromCustomerId'] = array('eq', $value['cid']);
            $productWhere2['supportSpecification'] = array('eq', 1);
            $productSpeciList = $module_product->where($productWhere2)->select();
            foreach($productSpeciList as $key1 => $proList){

                $speciWhere['pid'] = array('eq', $proList['id']);
                $speciWhere['inventoryCount'] = array('elt', $value['warnNum']);
                $speciList = $module_product_speci->where($speciWhere)->select();
                foreach($speciList as $key2 => $speci){
                    $goodList2 = [
                        'name' => $proList['name'].':'.$speci['firstSpecificName']  . $speci['secSpecificName'],
                        'warningListId' => $warningListId,
                        'pid' => $proList['id'],
                        'speciId' => $speci['id'],
                        'inventoryCount' => $speci['inventoryCount'],
                        'cid' => $value['cid'],
                        'cuId' => $value['cuId'],
                        'warnNum' => $value['warnNum'],
                        'serialNumber' => $speci['serialNumber']
                    ];
                    $stock_warning_result->add($goodList2);
                    array_push($goodsList, $goodList2);
                }
            }
            $total = count($goodsList);
//            dump($goodsList);
            $this->sendWarning($goodsList, $cid, $cuId, $total);
        }
    }

    /**
     * 发送预警消息
     * @param $goodsList “预警商品”
     * @param $cid "平台id"
     * @param $cuId “接收人id”
     */
    protected function sendWarning($goodsList, $cid, $cuId, $total)
    {
        $head = '<h3>库存预警</h3><hr/><p>总数：'.$total.'</p><table border="1" cellspacing="0"><tr><td><b>商品名称</b></td><td><b>条码</b></td><td><b>警戒库存</b></td><td><b>目前实际库存</b></td></tr>';
        $arr_message = [$head];
        foreach($goodsList as $key => $value){
            $body = '<tr><td>'.$value['name'].'</td><td>'.$value['serialNumber'].'</td><td>'.$value['warnNum'].'</td><td>'.$value['inventoryCount'].'</td></tr>';
            $arr_message[] = $body;
        }
        $arr_message[] = '</table>';
        $message = implode('', $arr_message);
//        echo $message;
        PlatMessageAction::pushMessage('库存预警', $message, $cuId, '', 0, '', '', 2, 0, 0,0, '', $cid);
    }

    /**
     * 获取user
     */
    public function getUser($page, $listRows)
    {
        /** 1. 判断是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        Session::switchCustomer(0);
        $customer_user = M('customer_user');
        Session::switchCustomer(Session::$user["customerId"]);

//        $where['customerId'] = 3;
        $where['customerId'] = Session::$user["customerId"];
        $where['status'] = 'open';
        $user = $customer_user->where($where)
            ->field('loginName, fullName, phone, id')
            ->page($page, $listRows)
            ->select();

        if ($user) {
            Output::instance()->object([
                'code' => 0,
                'msg' => '获取成功',
                'data' => $user
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '获取失败'
            ]);
        }
    }
}